//
//  MHHomeCircleItemCollectionViewCell.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/4/13.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHHomeCircleItemCollectionViewCell.h"
#import <WZLBadge/UIView+WZLBadge.h>
#import "MHIMMessageTransferHelper.h"
#import "MHCircleUpdateModel.h"
#import <WZLBadge/UIView+WZLBadge.h>
@interface MHHomeCircleItemCollectionViewCell()



@property (weak, nonatomic) IBOutlet UIImageView *circleBgImagView;
@property (weak, nonatomic) IBOutlet UIView *videoContainerView;
@property (weak, nonatomic) IBOutlet UILabel *videoDurationTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *circleNameLabel;
@property (weak, nonatomic) IBOutlet UIButton *circleOwnerBtn;
@property (weak, nonatomic) IBOutlet UIImageView *showdowView;
@property (weak, nonatomic) IBOutlet UILabel *postionLabel;
@end

@implementation MHHomeCircleItemCollectionViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.circleBgImagView.contentMode = UIViewContentModeScaleAspectFill;
    self.circleBgImagView.masksToBounds = YES;
    self.circleNameLabel.font = MHRegularFont_15;
//    self.circleBgImagView.layer.masksToBounds = YES;
    self.circleNameLabel.adjustsFontSizeToFitWidth = YES;
    self.redDotView.hidden = YES;
    self.postionLabel.font = MHRegularFont_12;
    self.KVOController = [FBKVOController controllerWithObserver:self];

//    self.containerView.layer.shadowColor = MHCircleShadowColor.CGColor;
//    self.containerView.layer.shadowOpacity = 0.5;
//    self.containerView.layer.shadowOffset = CGSizeMake(1, 3);
//    self.circleBgImagView.userInteractionEnabled = YES;
}

- (void)bindViewModel:(MHHomeCirleItemViewModel *)viewModel{
    self.viewModel = viewModel;
    [self.showdowView clearBadge];
    
    if(viewModel.homeCircle.title.length > 5)
    {
        
        self.circleNameLabel.text = [NSString stringWithFormat:@"%@...",[viewModel.homeCircle.title substringWithRange:NSMakeRange(0, 5)]];
    }else
    {
       self.circleNameLabel.text = viewModel.homeCircle.title;
    }
    if (viewModel.homeCircle.location.isShowLocation) {
        self.postionLabel.text = viewModel.homeCircle.location.areaName;
    }else
    {
        self.postionLabel.text = @"";
    }
    
    [self.circleBgImagView yy_setImageWithURL:[NSURL URLWithString:viewModel.homeCircle.fullCoverUrl] placeholder:MHCircleBgPlaceHolder()];
    
    
//    TIMConversation * conversation = [[TIMManager sharedInstance] getConversation:TIM_GROUP receiver:viewModel.homeCircle.circleCode];
//    IMAConversation *imaCover =  [[IMAConversation alloc] initWith:conversation];
//    self.imaConver = imaCover;
    [self.KVOController unobserveAll];

    __weak __typeof(self)weakSelf = self;
    [self.KVOController observe:self.imaConver keyPath:@"unReadCount" options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) {
        [weakSelf.showdowView showBadgeWithStyle:WBadgeStyleNumber value:self.imaConver.unReadCount animationType:WBadgeAnimTypeNone];
    }];
    
    
    [self.KVOController observe:self.imaConver keyPath:@"lastMessage.status" options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) {
        [weakSelf.showdowView showBadgeWithStyle:WBadgeStyleNumber value:self.imaConver.unReadCount animationType:WBadgeAnimTypeNone];
    }];
    [self.KVOController observe:self.imaConver keyPath:@"lastMessage" options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) {
        [weakSelf.showdowView showBadgeWithStyle:WBadgeStyleNumber value:self.imaConver.unReadCount animationType:WBadgeAnimTypeNone];
    }];
    
    self.showdowView.badgeCenterOffset = CGPointMake(-self.circleBgImagView.width*0.25, self.circleBgImagView.height -10);
    if (self.imaConver && self.imaConver.unReadCount > 0) {
        [self.showdowView showBadgeWithStyle:WBadgeStyleNumber value:self.imaConver.unReadCount animationType:WBadgeAnimTypeNone];
    }else
    {
        [self.showdowView showBadgeWithStyle:WBadgeStyleNumber value:0 animationType:WBadgeAnimTypeNone];
    }

    
//    [self loadLastConversationMessage];
   
    
}


-(void) lastMessage
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if ([AXAppDelegate sharedDelegate].imGroupImMessageUpdate) {
            NSString *value = [[AXAppDelegate sharedDelegate].imGroupImMessageUpdate objectForKey:self.viewModel.homeCircle.circleCode];
            NSMutableDictionary *dic = [AXAppDelegate sharedDelegate].imGroupImMessageUpdate;
            if (value.length > 0 && ![value isEqualToString:self.imaConver.lastMessage.msg.msgId] ) {
                self.redDotView.hidden = false;
            }else
            {
                self.redDotView.hidden = YES;
               
            }
            
        }else
        {
            self.redDotView.hidden = YES;
            
        }
    });
}

-(void) loadLastConversationMessage
{
    if (self.imaConver.lastMessage) {
        [self lastMessage];
    }else
    {
        __weak __typeof(self)weakSelf = self;
        [self.imaConver asyncLoadLocalLastMsg:^{
            
            if (self.imaConver.lastMsg == nil) {
                self.redDotView.hidden = YES;
                return;
            }
            [weakSelf lastMessage];
            NSString *value = [[AXAppDelegate sharedDelegate].imGroupImMessageUpdate objectForKey:self.viewModel.homeCircle.circleCode];
            NSMutableDictionary *dic = [AXAppDelegate sharedDelegate].imGroupImMessageUpdate;
            if (!value) {
                if (self.imaConver.lastMessage.msg) {
                    [[AXAppDelegate sharedDelegate].imGroupImMessageUpdate setObject:self.imaConver.lastMessage.msg.msgId forKey:self.viewModel.homeCircle.circleCode];
                    self.viewModel.homeCircle.msgId = self.imaConver.lastMessage.msg.msgId;
                    [[MHIMMessageTransferHelper sharedInstance] chacheIMMessageWithName:MHChacheIMGroupLastMessage model:self.viewModel.homeCircle];
                }
            }
        }];
        
        
        if (self.imaConver.lastMsg == nil) {
            self.redDotView.hidden = YES;
        }
    }

}

- (void)dealloc
{
    [self.KVOController unobserveAll];
    self.KVOController = nil;
}


-(IMAConversation *)imaConver
{
//    if (!_imaConver) {
        IMAConversationManager *mgr = [IMAPlatform sharedInstance].conversationMgr;
        CLSafeMutableArray *conversationLists  = [mgr conversationList];
        NSArray *fliterArr =  [conversationLists.safeArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"receiver == '%@'",self.viewModel.homeCircle.circleCode]]];
        if (fliterArr.count) {
            _imaConver = [fliterArr lastObject];
        }else
        {
            _imaConver = nil;
        }

//    }
    return _imaConver;
}



@end
